import mitt from 'mitt';

class Message{
    constructor(){
        this.event=mitt();
        this.init();
    }
    //初始化监听事件
    init(){

        /**
            //在raymond-app中的jscore中发送消息
            this.worker.postMessage({
                type:'test',
                body:{
                    a:1
                }
            })
            //接收消息，this.event就是mitt,this.event.emit发送，this.event.on接收
            global.addEventListener('message',(e)=>{
                const msg=e.data;
                const {type,body}=msg;
                this.event.emit(type,body)
            })
        */

        //执行后解构，然后出发receive函数
        global.addEventListener('message',(e)=>{
            // console.log("逻辑线程：",e)
            const msg=e.data;
            // console.log("逻辑线程：",msg)
            const {type,body}=msg;
            this.event.emit(type,body)
        })
    }
    //监听接收消息
    receive(type,callback){
        this.event.on(type,callback);
    }
    //往原生层发送消息
    send(msg){
        global.postMessage(msg);
    }
    //发送消息和接收消息
    sendAndReceive(opts){
        const {type='trrigerWXApi',body={apiName:'',params:{}},callback=()=>{}}=opts;
        this.send({
            type,
            body
        })
        this.receive(body.apiName,callback)
    }
}

export default new Message();